<template>
  <div class="flow-designer">
    <div>
      <el-input v-model="inputName" style="width: 30vh;margin-left: 2vh;float: left;margin-top: 2vh;" placeholder="输入审批名"/>
      <el-button plain @click="getApproval(pageCount)" style="width: 10vh;float: left;margin-top: 2vh;margin-left: 2vh">查询审批项</el-button>
      <el-button plain @click="inputName='',getApproval(pageCount)" type="info" style="width: 10vh;float: left;margin-top: 2vh;margin-left: 2vh">所有审批项</el-button>
      <el-button type="primary" @click="deApproval = true;isEdit = false" style="float: right;margin-top: 2vh;margin-bottom: 1vh;margin-right: 2vh">定义审批项</el-button>
      <el-table :data="statuA" style="margin-left: 1vh;width: 150vh;border-radius: 10px;text-align: left" >
        <el-table-column prop="id" label="审批项编号" width="270"></el-table-column>
        <el-table-column prop="processName" label="审批项名" width="150"></el-table-column>
        <el-table-column prop="" label="步骤数" width="70"><template  #default="{row}">{{ row.configData.approvalSteps.length}}</template></el-table-column>
        <el-table-column label="编辑" width="100" >
          <template  #default="{row}"><el-button type="primary" @click="toEdit(row.id,row.configData,row.processName)">去编辑</el-button>   </template>
        </el-table-column>
        <el-table-column label="使用记录" width="100" ><template  #default="{row}">
          <el-button type="primary" @click="toDetail(row)">查看</el-button> </template>
        </el-table-column>
        <el-table-column prop= "createTime" label="创建时间" width="160"></el-table-column>
        <el-table-column label="审批项状态" width="220" >
          <template  #default="{row}">
            <div v-if="row.id!==''">
              <div v-if="row.status==='FREEZE'">暂停</div>
              <div v-if="row.status==='NORMAL'">正常</div>
            </div>

            <el-select v-model="row.type" placeholder="选择状态" style="width: 150px;float: right;margin-top: -23px" >
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
              />
            </el-select>   </template>
        </el-table-column>
        <el-table-column label="操作" width="100" >
          <template  #default="{row}"><el-button type="primary" :disabled="row.type===undefined" @click="updateStatus(row.id,row.type)">提交</el-button> </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin-top: 1vh;display: flex; justify-content: center;" background layout="prev, pager, next" :total="total"
                     v-model:page-size="pageSize"
                     v-model:current-page= "pageCount"
                    @change="getApproval()" />
    </div>
    <div >
      <el-dialog
          v-model="deApproval2"
          title="审批项使用记录"
          width="800"
      >
        <el-input v-model="inputName" style="width: 30vh;margin-left: 2vh;float: left;margin-top: 2vh;" placeholder="输入审批人名"/>
        <el-button plain @click="this.getInstances" style="width: 10vh;float: left;margin-top: 2vh;margin-left: 2vh">查询</el-button>
        <el-table :data="instances" style="margin-left: 1vh;width: 150vh;border-radius: 10px;text-align: left" >
          <el-table-column prop="approvalInstance.id" label="审批实例ID" width="150"></el-table-column>
          <el-table-column prop="approvalInstance.applicantId" label="发起审批人Id" width="150"></el-table-column>
          <el-table-column prop="startName" label="发起审批人" width="150"></el-table-column>
          <el-table-column prop= "approvalInstance.createTime" label="创建时间" width="160"></el-table-column>
          <el-table-column label="审批项状态" width="150" >
            <template  #default="{row}">
              <el-tag
                  :type="statusTypeMap[row.approvalInstance?.status]"
                  effect="light"
              >
                {{ statusTextMap[row.approvalInstance?.status] }}
              </el-tag>
              </template>
          </el-table-column>
        </el-table>
        <el-pagination style="margin-top: 1vh;display: flex; justify-content: center;" background layout="prev, pager, next"
                       :total="total2"
                       v-model:page-size="pageSize"
                       v-model:current-page= "pageCount2"
                       @change="getInstances()" />
      </el-dialog>
    </div>
    <div>
      <el-dialog
          v-model="deApproval"
          title="定义审批项"
          width="1000"
          :before-close="closeDefinition"
      >
    <div style="font-size: 30px;font-family: 华文楷体,serif;margin-bottom: 2vh">审批项名称:
      <el-input v-model="input" style="width: 30vh;margin-left: 2vh;" />
      <el-select
          v-model="type1"
          placeholder="选择审批项类型"
          size="large"
          style="width: 170px;margin-left: 2vh"
      >
        <el-option
            v-for="item in options3"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      <el-select-v2
          v-model="type2"
          :options="options4"
          placeholder="请选择提交选项控件"
          style="width: 170px;margin-left: 2vh"
          multiple
      />
    </div>
    <draggable
        v-model="steps"
        handle=".handle"
        @end="onDragEnd"
    >
      <div v-for="(step, index) in steps" :key="step.stepId" class="step-node">
        <div class="handle">第{{index+1}}步 ↓</div>
        <el-input style="width: 20%;height: 52px" v-model="step.stepName" placeholder="步骤名称"/>
        <el-input type="textarea" style="width: 20%" v-model="step.requirement" placeholder="审批要求"/>
        <el-select
            v-model="step.approveType"
            placeholder="审批职务"
            size="large"
            @click="getJob(index)"
            style="width: 240px;margin-left: 10px"
        >
          <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
          <el-select
              v-model="step.approvePeople"
              placeholder="审批人"
              size="large"
              :disabled="step.approveType===''"
              @click="getUser(step.approveType)"
              style="width: 240px"
          >
            <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
        </el-select>
        <el-button type="danger" @click="removeStep(index)">×</el-button>
      </div>
    </draggable>
    <div class="flow-designer">
      <el-button :disabled="input===''"  @click="addStep" style="width: 200px;margin-top: 10px">添加步骤</el-button>
      <el-button :disabled="steps.length===0" type="success" @click="submitApproval" style="width: 200px;margin-top: 10px">提交</el-button>
      <el-button type="danger" @click="closeDefinition()" style="width: 200px;margin-top: 10px">取消</el-button>
      <el-button type="primary" @click="deApproval=false" style="width: 200px;margin-top: 10px">暂存</el-button>
    </div>
    </el-dialog>
  </div></div>
</template>

<script>
import {VueDraggableNext} from 'vue-draggable-next'
import {onMounted, ref} from "vue";
import {getJobs, getJobUsers, userUpdateName} from "@/api/user.js";
import {ElMessage} from "element-plus";
import useUserInfoStore from "@/stores/userInfo.js";
import {deApproval, getApprovals, getInstanceInfo, updateStatusById} from "@/api/Approval.js";
import HistoryApproval from "@/views/common/HistoryApproval.vue";
import userInfo from "@/stores/userInfo.js";
export default {

  components: {HistoryApproval, draggable: VueDraggableNext },
  data() {
    const options1 = [

    ]
    const options2 = [

    ]
    const options = [
      {
        value: "normal",
        label: '正常',
      },
      {
        value: "freeze",
        label: '暂停',
      },
      {
        value: "delete",
        label: '删除',
      },
    ]
    const options3 = [{value: 1, label: '财务'},{value: 2, label: '人事'},{value: 3, label: '行政'}]
    const options4 =  [{value: 'text', label: '文本输入'},{value: 'daterange', label: '时间'},{value: 'file', label: '文件'},{value: 'number', label: '数字'}]
    const userInfoStore = useUserInfoStore()
    const statusTypeMap = {
      'RETRIEVE': 'info',
      'PENDING': 'warning',
      'APPROVED': 'success',
      'REJECTED': 'danger'
    }

    const statusTextMap = {
      'RETRIEVE': '已撤回',
      'PENDING': '审批中',
      'APPROVED': '已通过',
      'REJECTED': '已驳回'
    }
    const statuA = ref([
    ],)
    return {
      steps: [], // 绑定流程步骤数据
      options1:[],
      options2:[],
      deApproval: false,
      deApproval2: false,
      input: '',
      statuA,
      options,
      type1: '',
      type2: '',
      options3,
      options4,
      userInfoStore,
      instances: [],
      total:1,
      total2:1,
      pageSize:4,
      pageCount:1,
      pageCount2:1,
      inputName:null,
      processId:'',
      isEdit:false,
      statusTextMap,
      statusTypeMap,
      temId:null
    }
  },
  methods: {
    addStep() {
      this.steps.push({
        stepId: `step_${Date.now()}`,
        stepName: '',
        requirement: '',
        approveType: '',
        approveTarget: '',
        approvePeople: ''
      })
    },
    removeStep(index) {
      this.steps.splice(index, 1)
    },
    async submitApproval() {
      const approvalData = {
        approvalItem: {
          type: this.type1,
          controls: this.type2
        },
        approvalSteps: this.steps.map((step, index) => ({
          stepId: step.stepId,
          order: index + 1, // 根据顺序生成
          stepName: step.stepName,
          requirement: step.requirement,
          approveType: step.approveType,
          approvePeople: step.approvePeople
        }))
      };

      // 这里可以发送 approvalData 到后端
      let res,type
      try {
        if (this.isEdit){
          type = 1
          this.isEdit = false
        }else {
          type = 0
        }
        res = await deApproval(this.input,this.userInfoStore.info.enterpriseId,this.userInfoStore.info.id, JSON.stringify(approvalData, null, 2),type,this.processId)
        ElMessage.success(res || '定义成功')
        await this.getApproval()
        this.closeDefinition()
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '定义失败')
      }
    },
    async getJob(index) {
      this.options1 = await getJobs(this.userInfoStore.info.enterpriseId)
      this.steps[index].approvePeople = ''
    },
    async getUser(approveType) {
      this.options2 = await getJobUsers(this.userInfoStore.info.enterpriseId,approveType)
    },
    async updateStatus(id,status) {
      let res = await updateStatusById(id,status)
      ElMessage.success(res)
      await this.getApproval()
    },
    async getApproval() {
      // this.pageCount = Math.ceil(this.total/this.pageSize)
      let res = await getApprovals(this.inputName,this.userInfoStore.info.enterpriseId,this.pageCount,this.pageSize)
      if (res.total!==undefined) {
        this.total = res.total
      }
      this.statuA = res.list
      if (this.statuA !== undefined){
        for (let i = 0; i < this.statuA.length; i++) {
          this.statuA[i].configData = JSON.parse(this.statuA[i].configData)
        }
      }
      // console.log(Math.ceil(this.total/this.pageSize))
    },
    closeDefinition() {
      this.deApproval=false
      this.input=''
      this.steps = []
      this.type1 = ''
      this.type2 = ''
    },
    toEdit(id,info,name){
      this.input = name
      this.type1 = info.approvalItem.type
      this.type2 = info.approvalItem.controls
      this.steps = info.approvalSteps
      this.deApproval=true
      this.processId = id
      this.isEdit = true
      console.log(this.processId)
    },
    toDetail(row){
      this.processId = row.id
      this.getInstances()
      this.deApproval2 = true
    },
    async getInstances(){
      this.pageCount2 = Math.ceil(this.total2/this.pageSize)
      let res = await getInstanceInfo(this.processId,this.inputName,this.pageCount2,this.pageSize)
      if (res.total!==undefined) {
        this.total2 = res.total
      }
      this.instances = res.list
    },

  },
  mounted() {
    this.getApproval() // 页面加载时自动执行
  }
}

</script>

<style scoped lang="scss">
.flow-designer {
  text-align: center;
  position: relative;
}

</style>
